from fastapi import FastAPI, HTTPException
import uvicorn
from sqlalchemy import create_engine, Column, Integer, String, BigInteger
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, Session
from pydantic import BaseModel
import os
from typing import List
import logging

from opentelemetry import trace

tracer = trace.get_tracer(__name__)
logger = logging.getLogger(__name__)


app = FastAPI()



DATABASE_URL = os.getenv(
    "DATABASE_URL", "postgresql://app_user:app_password@postgres:5432/app_db"
)

engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()


class Room(Base):
    __tablename__ = "room"

    id = Column(BigInteger, primary_key=True, index=True)
    title = Column(String(255), nullable=False)
    price = Column(Integer, nullable=False)
    location = Column(String(255))


class RoomResponse(BaseModel):
    id: int
    title: str
    price: int
    location: str

    class Config:
        from_attributes = True


class BookingRequest(BaseModel):
    name: str
    phone: str
    message: str = ""


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


@app.get("/rooms", response_model=List[RoomResponse])
async def get_rooms():
    logger.info("开始获取房屋列表")
    db = SessionLocal()
    try:
        rooms = db.query(Room).all()
        logger.info(f"成功获取 {len(rooms)} 个房屋信息")
        return rooms
    except Exception as e:
        logger.error(f"获取房屋列表失败: {str(e)}")
        raise
    finally:
        db.close()


@app.post("/rooms/{room_id}")
async def book_room(room_id: int, booking: BookingRequest):
    with tracer.start_as_current_span("book_room"):
        current_span = trace.get_current_span()
        current_span.add_event("Booking room")
        logger.info(f"收到房屋 {room_id} 的预约请求，用户: {booking.name}")

    db = SessionLocal()
    try:
        room = db.query(Room).filter(Room.id == room_id).first()
        if not room:
            logger.warning(f"房屋 {room_id} 不存在")
            raise HTTPException(status_code=404, detail="房屋不存在")

        logger.info(
            f"预约成功 - 房屋: {room.title}, 用户: {booking.name}, 电话: {booking.phone}"
        )
        return {
            "message": "预约成功",
            "room_title": room.title,
            "booking_info": {
                "name": booking.name,
                "phone": booking.phone,
                "message": booking.message,
            },
        }
    except Exception as e:
        logger.error(f"预约失败: {str(e)}")
        raise
    finally:
        db.close()


@app.get("/")
async def root():
    return {"message": "User Backend API"}


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000, log_config=None)
